import type { Effect, Reducer } from 'umi';

import { getTeacherId, queryCurrent } from '@/services/user';

export interface ButtonPermission {
  type: string,
  text: string,
  url: string,
}

export interface Menu {
  buttons?: ButtonPermission[],
  routes?: RoutePermission[],
}

export let menus: Menu = {};

export interface CurrentUser {
  icon1?: string;
  name?: string;
}

export interface RoutePermission {
  name: string,
  path: string,
  routes?: RoutePermission[],
}

export interface UserModelState {
  currentUser?: CurrentUser;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    // fetch: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
  },

  effects: {
    // *fetch(_, { call, put }) {
    //   const response = yield call(queryUsers);
    //   yield put({
    //     type: 'save',
    //     payload: response,
    //   });
    // },
    *fetchCurrent(_, { call, put }) {
      // const response = yield call(queryCurrent);
      // yield put({
      //   type: 'saveCurrentUser',
      //   payload: response,
      // });

      const response = yield call(queryCurrent);
      if (response) {
        menus = response;
      }

      const res = yield call(getTeacherId)
      localStorage.setItem('teacherId', res?.result?.userId)

      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
  },
  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default UserModel;
